<template>
  <view class="common-bg">
    <view class="pad-20">
      <view class="flex flex-center flex-between">
        <view class="font-24 col-000-8 font-600">
          {{ $t('list.devices') }}
        </view>
        <view class="flex">
          <view class="msg-box" @click="doMsg">
            <uni-badge class=" uni-badge-left-margin" :text="msgNum" absolute="rightTop" :offset="[-3, -3]" size="small">
              <image class="msg-img" src="/static/svg/msg.svg" mode=""></image>
            </uni-badge>
          </view>
          <view class="add-box" @click="doAdd">
            <view class="add">
              <image class="img" src="/static/svg/add.svg" mode="widthFix"></image>
            </view>
          </view>
        </view>
      </view>
      <!-- 我的设备 -->
      <view class="devices-list">
        <view class="item" v-for="(item, index) in deviceList" :key="item.id" @click="doDetail(item.id)">
          <view class="device">
            <image v-if="item.device_status === 1" class="img" src="/static/svg/devices.svg" mode="widthFix"></image>
            <image v-else class="img" src="/static/svg/devices-000.svg" mode="widthFix"></image>
          </view>
          <view class="name font-500 font-16 col-000-8">
            {{item.device_name}}
          </view>
          <view class="status font-16 col-000-4">
            <span class="dot" :class="{'no': item.device_status == 0}"></span>
            {{item.device_status === 1 ? $t('list.online') : $t('list.offline') }}
          </view>
        </view>
      </view>
      <view class="empty-box" v-if="deviceList.length == 0">
        <view class="">
        	<view class="empty-img">
        	  <image class="img-100" src="/static/svg/empty.svg" mode="widthFix"></image>
        	</view>
        	<view class="empty-text">
        	  {{ $t('list.noDevice') }}
        	</view>
        </view>
      </view>
    </view>
  </view>
</template>
<script>
	import deviceApi from '@/api/device.js';
	import messageApi from '@/api/message.js';
	import mqttApi from '@/api/my-mqtt.js';
	import {store} from '@/uni_modules/uni-id-pages/common/store.js'
	
export default {
  data() {
    return {
      msgNum: 0,
      deviceList: [],
      mqttConnected: false
    }
  },
	created() {
		// 只有在已登录状态下才调用需要权限的接口
		if (store.hasLogin) {
			this.initMqttConnection();
			this.getDeviceListApi();
			this.getMsgNum()
		} else {
			console.log('[LIST] 用户未登录,跳过设备列表和消息获取')
		}
	},
	beforeDestroy() {
		// 断开真实MQTT连接
		console.log('[DEVICE_LIST] 页面销毁，断开真实MQTT连接');
		mqttApi.disconnect();
	},
  methods: {
		/**
		 * 初始化MQTT连接
		 */
		async initMqttConnection() {
			try {
				console.log('[DEVICE_LIST] 初始化真实MQTT连接...');
				
				// 监听MQTT连接状态变化
				mqttApi.onConnectionChange((connected) => {
					this.mqttConnected = connected;
					console.log('[DEVICE_LIST] 真实MQTT连接状态变化:', connected);
					
					if (connected && this.deviceList.length > 0) {
						// 连接成功后订阅所有设备状态
						this.subscribeAllDevicesStatus();
					}
				});
				
				// 使用配置的用户名密码连接真实MQTT服务器
				// 连接到 ka1e5a49.ala.cn-hangzhou.emqxsl.cn
				await mqttApi.connect({
					username: 'linyuchi',
					password: 'adSd@@4d'
				});
				
				console.log('[DEVICE_LIST] 真实MQTT连接成功');
				
				// 如果设备列表已经加载，订阅设备状态
				if (this.deviceList.length > 0) {
					await this.subscribeAllDevicesStatus();
				}
				
			} catch (error) {
				console.error('[DEVICE_LIST] 真实MQTT连接失败:', error);
				uni.showToast({
					title: '设备通信连接失败',
					icon: 'none',
					duration: 2000
				});
			}
		},
		
		/**
		 * 订阅所有设备的状态
		 */
		async subscribeAllDevicesStatus() {
			if (!this.mqttConnected || this.deviceList.length === 0) {
				console.log('[DEVICE_LIST] 真实MQTT未连接或设备列表为空，跳过订阅');
				return;
			}
			
			console.log('[DEVICE_LIST] 开始订阅所有设备的真实状态...',this.deviceList);
			
			for (const device of this.deviceList) {
				if (device.sn) {
          console.log('[DEVICE_LIST] 订阅设备真实状态:', device.sn);

					try {
						// 使用真实MQTT API订阅设备心跳状态
						await mqttApi.subscribeDeviceStatus(device.sn, (topic, message) => {
							this.handleDeviceStatus(device.sn, message);
						});
						
						console.log(`[DEVICE_LIST] 设备 ${device.sn} 真实状态订阅成功`);
					} catch (error) {
						console.error(`[DEVICE_LIST] 设备 ${device.sn} 状态订阅失败:`, error);
					}
				}
			}
		},
		
		/**
		 * 处理设备状态消息
		 * @param {string} deviceSn 设备SN码
		 * @param {Object} message 状态消息
		 */
		handleDeviceStatus(deviceSn, message) {
			console.log(`[DEVICE_LIST] 收到设备 ${deviceSn} 真实心跳消息:`, message);
			
			// 根据真实心跳消息格式解析设备在线状态
			let isOnline = false;
			
			if (typeof message === 'object') {
				// 真实心跳消息格式: {"hb":true,"ts":1446894,"sn":"340766215788","on":true,"heap":70,"rssi":-67,"ver":"2.4-OPT","draw":true,"pause":false,"pat":0,"state":1}
				// 判断 on 字段来确定设备是否在线
				if (message.hb === true && typeof message.on === 'boolean') {
					isOnline = message.on;
					
					// 记录额外的设备状态信息
					console.log(`[DEVICE_LIST] 设备 ${deviceSn} 详细状态:`, {
						在线状态: isOnline,
						信号强度: message.rssi,
						固件版本: message.ver,
						内存堆: message.heap,
						绘画状态: message.draw,
						暂停状态: message.pause,
						当前图案: message.pat,
						设备状态: message.state,
						时间戳: message.ts
					});
				} else {
					// 兼容其他可能的消息格式
					isOnline = message.status === 'online' || message.online === true || message.connected === true;
				}
			} else if (typeof message === 'string') {
				// 如果消息是字符串，尝试解析JSON
				try {
					const parsedMessage = JSON.parse(message);
					if (parsedMessage.hb === true && typeof parsedMessage.on === 'boolean') {
						isOnline = parsedMessage.on;
					} else {
						isOnline = message.includes('online') || message.includes('connected');
					}
				} catch (e) {
					// JSON解析失败，按字符串处理
					isOnline = message.includes('online') || message.includes('connected');
				}
			}
			
			// 更新设备在线状态
			this.updateDeviceOnlineStatus(deviceSn, isOnline);
		},
		
		/**
		 * 更新设备在线状态
		 * @param {string} deviceSn 设备SN码
		 * @param {boolean} isOnline 是否在线
		 */
		updateDeviceOnlineStatus(deviceSn, isOnline) {
			// 更新设备列表中的状态
			const deviceIndex = this.deviceList.findIndex(device => device.sn === deviceSn);
			if (deviceIndex !== -1) {
				const currentStatus = this.deviceList[deviceIndex].device_status;
				const newStatus = isOnline ? 1 : 0;
				
				if (currentStatus !== newStatus) {
					console.log(`[DEVICE_LIST] 设备 ${deviceSn} 状态变更: ${currentStatus} -> ${newStatus}`);
					
					// 使用 Vue.set 确保响应式更新
					this.$set(this.deviceList[deviceIndex], 'device_status', newStatus);
					
					console.log(`设备 ${this.deviceList[deviceIndex].device_name} ${isOnline ? '已上线' : '已离线'}`);
				}
			}
		},
		
		
		getMsgNum() {
			messageApi.getUnreadCount().then(res => {
				this.msgNum = res.unreadCount;
			})
		},
		async getDeviceListApi() {
			try {
				const res = await deviceApi.getDeviceList();
				if(res.errCode === 0) {
					this.deviceList = res.data;
					console.log('[DEVICE_LIST] 获取设备列表成功:', this.deviceList);
					
					// 显示设备默认状态
					this.deviceList.forEach(device => {
						console.log(`[DEVICE_LIST] 设备 ${device.device_name}(SN: ${device.sn}) 默认状态: ${device.device_status === 1 ? '在线' : '离线'}`);
					});
					
					// 获取设备列表后，如果真实MQTT已连接，订阅所有设备的状态
					if (this.mqttConnected) {
						await this.subscribeAllDevicesStatus();
					} else {
						console.log('[DEVICE_LIST] 真实MQTT未连接，等待连接成功后订阅');
					}
				} else {
					console.error('[DEVICE_LIST] 获取设备列表失败:', res.errMsg);
					uni.showToast({
						title: res.errMsg || '获取设备列表失败',
						icon: 'none'
					});
				}
			} catch (error) {
				console.error('[DEVICE_LIST] 获取设备列表异常:', error);
				uni.showToast({
					title: '网络异常，请重试',
					icon: 'none'
				});
			}
		},
		doAdd() {
      uni.navigateTo({
        url: '/pages/list/add-device'
      })
    },
		doMsg() {
			uni.navigateTo({
				url: '/pages/list/message-list'
			})
		},
		doDetail(id) {
			uni.navigateTo({
				url: '/pages/list/detail?id=' + id
			})
		}
  }
}

</script>
<style lang="scss" scoped>

.devices-list {
  width: 100%;
  margin: 80rpx auto 0;

  .item {
    width: 100%;
    background-color: #fff;
    box-shadow: 0px 0px 8rpx 0px rgba(0, 0, 0, 0.08);
    border-radius: 16rpx;
    padding: 48rpx 0;
    margin-bottom: 32rpx;

    .device {
      width: 80rpx;
      height: 60rpx;
      margin: 0rpx auto 0;
      .img {
        width: 100%;
        height: 100%;
      }
    }

    .name {
      margin: 16rpx auto 0;
      text-align: center;
    }

    .status {
      text-align: center;
      margin: 8rpx auto 0;

      .dot {
        width: 12rpx;
        height: 12rpx;
        border-radius: 100%;
        margin-right: 8rpx;
        display: inline-block;
        background-color: #22C55D;

        &.no {
          background-color: rgba(0, 0, 0, 0.4);
        }
      }
    }
  }
}

.msg-box,
.test-box,
.add-box {
  width: 68rpx;
  height: 68rpx;
  border-radius: 100%;
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-left: 16rpx;
}

.test-box {
  background-color: #10B981;
  .test-text {
    color: #fff;
    font-size: 24rpx;
    font-weight: 500;
  }
}

.msg-img {
  width: 36rpx;
  height: 44rpx;
}

.img {
  width: 40rpx;
  height: 40rpx;
}

.add-box {
  background-color: #3C82F6;
  margin-left: 16rpx;
	display: flex;
	align-items: center;
	justify-content: center;
  .add {
		width: 40rpx;
		height: 40rpx;
    .img {
			width: 100%;
			height: 100%;
		}
  }
}
</style>